<template>
  <div v-loading="isLoading" class="panel-property">
    <div class="content">
      <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" :componentStyle="form.componentStyle" />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form state-switching-unique"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="30%"
      >
        <BaseOption :form="form" option="backgroundColor" :df-color="Variables.transparentBgColor" :required="true" />
        <VsFormItem :label="'数值类型'">
          <el-select v-model="form.valueType" :placeholder="$demoi18n('word.plsSelect')" size="default">
            <el-option
              v-for="(item, index) in [
                { label: '字符串', value: 'string' },
                { label: '数值', value: 'number' },
              ]"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </VsFormItem>
        <div class="top-btns">
          <el-button
            class="btn-sure"
            size="default"
            icon="CirclePlus"
            :disabled="addDisable"
            @click.stop="addNewRow(temp, item, 'data')"
          >
            {{ $demoi18n('btn.add') }}
          </el-button>
        </div>
        <el-table
          class="config-panel-table mapping-table"
          :data="form.data"
          :row-style="{ height: '25px' }"
          :header-row-style="{ height: '25px' }"
          max-height="235"
          :header-cell-style="{ lineHeight: '15px' }"
        >
          <el-table-column type="index" :label="$demoi18n('word.serialNumber')" width="60"></el-table-column>
          <el-table-column prop="icon" :label="$demoi18n('word.icon')" width="60">
            <template #default="scope">
              <IconEditor
                :icon="scope.row.icon"
                :componentStyle="form.componentStyle"
                :hasSync="true"
                :isAdaptive="form.isAdaptive"
                @save="saveIcon($event, scope.row)"
                @delete="deleteIcon($event, scope.row)"
                @sync="syncIcons($event, form.data)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            :label="`${form.valueType === 'string' ? '状态字符' : '状态阈值'}`"
            :min-width="`${form.valueType === 'string' ? 100 : 200}`"
          >
            <template #default="scope">
              <VsFormItem
                v-if="form.valueType === 'string'"
                :prop="`data[${scope.$index}].status`"
                :rules="
                  generateRules({
                    required: true,
                    max: 1000,
                  })
                "
              >
                <el-input
                  v-model="scope.row.status"
                  :placeholder="'请输入'"
                  size="default"
                  @blur="checkThreshold"
                ></el-input>
              </VsFormItem>
              <div v-else class="threshold-column">
                <VsFormItem
                  :prop="`data[${scope.$index}].min`"
                  :rules="
                    genRequireRule({
                      type: 'number',
                    })
                  "
                >
                  <el-input-number
                    v-model="scope.row.min"
                    :placeholder="$demoi18n('panel.thresholdSetting.leftVal')"
                    size="default"
                    :style="{ width: '100%' }"
                    :controls="false"
                    @blur="checkThreshold"
                    @keydown="clearInput"
                  ></el-input-number>
                </VsFormItem>
                <span :style="{ margin: '0 3px' }">-</span>
                <VsFormItem
                  :prop="`data[${scope.$index}].max`"
                  :rules="
                    genRequireRule({
                      type: 'number',
                    })
                  "
                >
                  <el-input-number
                    v-model="scope.row.max"
                    :placeholder="$demoi18n('panel.thresholdSetting.rightVal')"
                    size="default"
                    :style="{ width: '100%' }"
                    :controls="false"
                    @blur="checkThreshold"
                    @keydown="clearInput"
                  ></el-input-number>
                </VsFormItem>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="90" :label="$demoi18n('操作')">
            <template #default="scope">
              <el-button
                icon="SortUp"
                type="primary"
                :disabled="scope.$index === 0"
                link
                @click.stop="moveUp(scope.$index, scope.row, 'data')"
              ></el-button>
              <el-button
                icon="SortDown"
                type="primary"
                style="margin-left: 1px;"
                :disabled="scope.$index === form.data.length - 1"
                link
                @click.stop="moveDown(scope.$index, scope.row, 'data')"
              ></el-button>
              <el-button
                icon="Delete"
                type="primary"
                style="margin-left: 1px;"
                :disabled="delDisable"
                link
                @click.stop="deleteCurRow(scope.row, 'data')"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <OptionCollapse>
          <BaseOption :form="form" option="noDataPromptSetting" class="noDataPromptSetting" />
        </OptionCollapse>
        <VsFormItem>
          <el-checkbox v-model="form.isAdaptive">自适应组件宽高</el-checkbox>
        </VsFormItem>
      </el-form>
    </div>
  </div>
</template>
<script>
import BaseOption from '@/components/common/base-option/base-option.vue';
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import IconEditor from '@/components/common/icon/icon-editor.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import imgUploadBase from '@/mixin/img-upload-base.js';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import { getSrc } from '@/utils/util.js';
import orgConfig from './config';

export default {
  name: 'PanelProperty',
  components: {
    BaseOption,
    IconEditor,
    PanelLabelOverflowTooltip,
    VsFormItem,
    OptionCollapse,
  },
  mixins: [imgUploadBase, panelPropertyBase],
  data() {
    return {
      isLoading: false,
      form: {
        componentStyle: window._adoPremise.uc.theme,
      },
      dfCssStyleAttrs: {},
      delDisable: false,
      addDisable: false,
      item: {
        status: '',
        min: 0,
        max: 1,
        icon: '',
        iconSmall: '',
        uploadList: '',
        imgUrl: '',
      },
      temp: {},
      maxLen: 20,
      minLen: 1,
      curIndex: null,
      curChosen: '',
    };
  },
  computed: {

    // 将无图标的count配置项转化为this.form.data.length值，与带图标的组件逻辑统一
    count: {
      get() {
        return this.form.data.length;
      },
      set(v) {
        this.form.data = [];
        const count = v;
        for (let i = 0; i < count; i++) {
          this.temp = JSON.parse(JSON.stringify(this.item));
          this.form.data.push(this.temp);
        }
      },
    },
  },
  watch: {
    'form.data': {
      handler() {
        this.checkLimit();
      },
      deep: true,
    },
  },
  created() {
    if (orgConfig) {
      // 规避本地环境报错
      this.form = JSON.parse(JSON.stringify(orgConfig.config.property));
      this.form.data = this.form.data.map(item => {
        return getSrc(item);
      });
    }
    if (this.config) {
      this.form = JSON.parse(JSON.stringify(this.config.config.property));
      this.form.data = this.form.data.map(item => {
        return getSrc(item);
      });
    }
    this.dfCssStyleAttrs = this.initDfCssStyleAttrs();
    this.initMultiConfigData();
  },
  methods: {
    emitToPanel(error) {
      this.$message.error(error);
    },
    checkThreshold() {
      let errorText = '';
      if (this.form.valueType === 'string') {
        const textArray = this.form.data.map(item => item.status).filter(status => status !== '');
        const textSet = new Set(textArray);
        textSet.delete('');
        if (textSet.size < textArray.length) {
          errorText = this.$demoi18n('message.duplicateStringThreshold');
          this.emitToPanel(errorText);
          return false;
        }
      } else {
        const rangeArray = [];
        this.form.data.forEach((item, index) => {
          rangeArray[index] = [item.min, item.max];
        });
        for (let i = 0; i < rangeArray.length; i++) {
          if (rangeArray[i][0] >= rangeArray[i][1]) {
            errorText = this.$demoi18n('message.wrongThresholdRange');
            this.emitToPanel(errorText);
            return false;
          }
        }
        for (let i = 0; i < rangeArray.length; i++) {
          for (let j = 0; j < i; j++) {
            if (
              (rangeArray[i][0] >= rangeArray[j][0] && rangeArray[i][0] < rangeArray[j][1]) ||
              (rangeArray[i][1] > rangeArray[j][0] && rangeArray[i][1] < rangeArray[j][1])
            ) {
              errorText = this.$demoi18n('message.thresholdRepetition');
              this.emitToPanel(errorText);
              return false;
            }
          }
        }
      }
      return true;
    },
    moveUp(index, row, group) {
      if (index <= 0) {
        return;
      }
      const temp = this.form[group][index - 1];
      this.form[group].splice(index - 1, 1);
      this.form[group].splice(index, 0, temp);
    },
    moveDown(index, row, group) {
      const temp = this.form[group][index + 1];
      this.form[group].splice(index + 1, 1);
      this.form[group].splice(index, 0, temp);
    },
    initMultiConfigData() {
      const { count } = this;
      for (let i = count; i < this.minLen; i++) {
        this.temp = JSON.parse(JSON.stringify(this.item));
        this.form.data.push(this.temp);
      }

      this.delDisable = this.count <= this.minLen;
      this.addDisable = this.count >= this.maxLen;
    },
    addNewRow(temp, item, group) {
      const _temp = JSON.parse(JSON.stringify(item));
      this.form[group].push(_temp);
      if (this.count >= this.minLen) {
        this.delDisable = false;
      }
      if (this.count >= this.maxLen) {
        this.addDisable = true;
      }
    },
    deleteCurRow(item, group) {
      const index = this.form[group].indexOf(item);
      this.form[group].splice(index, 1);
      if (this.count <= this.minLen) {
        this.delDisable = true;
      }
      if (this.count <= this.maxLen) {
        this.addDisable = false;
      }
      this.form.valueType === 'string' && this.checkThreshold();
    },
    checkLimit() {
      const isValidThreshold = this.checkThreshold();
      if (!isValidThreshold) {
        return false;
      }
      const { data } = this.form;
      const nameList = data.map(n => n.name).filter(n => n);
      const aliasList = data.map(n => n.alias).filter(n => n);
      const nameListU = Array.from(new Set(nameList));
      const aliasListU = Array.from(new Set(aliasList));
      if (nameList.length !== nameListU.length || aliasList.length !== aliasListU.length) {
        this.$message.error(this.$demoi18n('message.nameOrAliasRepeated'));
        return false;
      }
      return true;
    },
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    saveIcon(iconConf, item) {
      item.icon = { ...iconConf, isAdaptive: this.form.isAdaptive };
    },

    // 清除数字输入框的 e
    clearInput(e) {
      const { key } = e;
      if (key === 'e' || key === 'E') {
        e.returnValue = false;
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../common/less/panel-property.less';
.panel-property {
  .content {
    .prop-form {
      padding: 0 10px;

      .threshold-column {
        display: flex;
        align-items: center;
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
      }
      .input-number {
        width: 80px;
        :deep(.el-input-number__decrease) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input-number__increase) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input__inner) {
          padding-left: 19px;
          padding-right: 19px;
        }
      }
      .input-number-left {
        margin-right: 25px;
      }

      .color-radio-group {
        background-color: #eeeeee;
        :deep(.el-radio-button__inner) {
          display: inline-block;
          padding: 2px 2px;
          border: 0;
          border-radius: 0;
          height: 24px;
          margin: 2px 2px;
          background: #eeeeee;
        }
        :deep(.is-active) {
          .el-radio-button__inner {
            background-color: #409eff;
          }
        }
      }
    }
  }
}
</style>
